package net.receiving.tcp;

import java.util.concurrent.BlockingQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.AbstractMap;
import java.util.Map;
import java.net.Socket;
import java.net.InetAddress;
import java.io.*;

/**
 * Created by HREN_VAM.
 */
public class TCPConnection implements Runnable {

    private final BlockingQueue<Map.Entry<InetAddress, List<Byte>>> queue;
    private final Socket socket;

    public TCPConnection(Socket socket, BlockingQueue<Map.Entry<InetAddress, List<Byte>>> queue) {
        this.queue = queue;
        this.socket = socket;
    }

    public void run() {
        try {
            InputStream in = socket.getInputStream();

            List<Byte> list = new ArrayList<Byte>();
            int nextByte;
            int countByte = 0;
            while ((nextByte = in.read()) != -1) {
                list.add((byte) nextByte);
                countByte ++;
            }
            queue.offer(new AbstractMap.SimpleImmutableEntry<InetAddress, List<Byte>>(socket.getInetAddress(), list));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
